package com.practice.dao.impl.user;

import com.practice.dao.user.UserDao;
import com.practice.domain.user.User;
import com.practice.exception.PracticeException;
import com.practice.util.IJdbcTemplate;

import javax.sql.DataSource;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

/**
 * Created by Administrator on 2016/8/20.
 */
@Repository
public class UserDaoImpl implements UserDao {
  private JdbcTemplate jdbcTemplate;

  public User detail(final Long id) {
    String sql = "SELECT * FROM t_user WHERE id = ?";
    return jdbcTemplate.queryForObject(sql, rowMapper(), id);
  }

  public User findByEmail(String email) {
    String sql = "SELECT * FROM t_user WHERE email = ?";
    return jdbcTemplate.queryForObject(sql, rowMapper(), email);
  }

  public User findByUsername(String username) {
    String sql = "SELECT * FROM t_user WHERE username = ?";
    return jdbcTemplate.queryForObject(sql, rowMapper(), username);
  }

  public User create(String username, String email, String password) throws PracticeException {
    String sql = "INSERT INTO t_user (username, email, password) values (?, ?, ?)";
    int count = jdbcTemplate.update(sql, username, email, password);
    if (count != 1) {
      throw new PracticeException("注册失败！");
    }
    return findByUsername(username);
  }

  private RowMapper<User> rowMapper() {
    return new RowMapper<User>() {
      public User mapRow(ResultSet rs, int rowNum) throws SQLException {
        User user = new User();
        user.setId(rs.getLong("id"));
        user.setUsername(rs.getString("username"));
        user.setEmail(rs.getString("email"));
        user.setPassword(rs.getString("password"));
        return user;
      }
    };
  }

  @Autowired
  public void setDataSource(DataSource dataSource) {
    this.jdbcTemplate = new IJdbcTemplate(dataSource);
  }
}
